﻿namespace Microsoft.VisualStudio.ServiceModel.DomainServices.Tools
{
    using EnvDTE;
    using EnvDTE80;
    using Microsoft.VisualStudio.OLE.Interop;
    using Microsoft.VisualStudio.Shell;
    using Microsoft.VisualStudio.Shell.Interop;
    using Microsoft.VisualStudio.TemplateWizard;
    using Microsoft.VisualStudio.Web.Silverlight;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices;

    public class BusinessApplicationProjectTemplateWizard : IWizard
    {
        private object[] _customParams;
        private DTE2 _dte2;
        private Dictionary<string, string> _replacementsDictionary;
        private Project _selectedSolutionFolder;
        private Solution2 _solution2;
        private string _webProjectName;

        public void BeforeOpeningFile(ProjectItem projectItem)
        {
        }

        private ProjectItem GetAspxTestPage(Project project)
        {
            string testPage = this._dte2.Globals["safeclientprojectname"] + "TestPage.aspx";
            return project.ProjectItems.Cast<ProjectItem>().FirstOrDefault<ProjectItem>(item => item.Name.Equals(testPage, StringComparison.OrdinalIgnoreCase));
        }

        private Project GetProject(string projectName)
        {
            Project project = null;
            if (this._selectedSolutionFolder != null)
            {
                project = GetProject(from p in this._selectedSolutionFolder.ProjectItems.Cast<ProjectItem>()
                    where p.SubProject != null
                    select p.SubProject, projectName);
            }
            return (project ?? GetProject(this._dte2.Solution.Projects.Cast<Project>(), projectName));
        }

        private static Project GetProject(IEnumerable<Project> projects, string projectName)
        {
            foreach (Project project in projects)
            {
                if (Path.GetFileNameWithoutExtension(project.FullName).Equals(projectName))
                {
                    return project;
                }
            }
            return null;
        }

        private Project GetSilverlightProject()
        {
            string projectName = this._replacementsDictionary["$safeprojectname$"];
            return this.GetProject(projectName);
        }

        private Project GetWebProject()
        {
            return this.GetProject(this._webProjectName);
        }

        public void ProjectFinishedGenerating(Project project)
        {
        }

        public void ProjectItemFinishedGenerating(ProjectItem projectItem)
        {
        }

        public void RunFinished()
        {
            Project silverlightProject = this.GetSilverlightProject();
            if ((this._customParams.Length > 0) && (this._customParams[0] != null))
            {
                string str = Path.GetDirectoryName((string) this._customParams[0]);
                string path = Path.Combine(str, "BA.Web");
                if (!Directory.Exists(path))
                {
                    path = Path.Combine(str, "BusinessApplication.Web");
                }
                string fileName = Path.Combine(path, "server.vstemplate");
                string destination = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(silverlightProject.FullName)), this._webProjectName);
                this._solution2.AddFromTemplate(fileName, destination, this._webProjectName, false);
            }
            Project webProject = this.GetWebProject();
            if (webProject != null)
            {
                this._dte2.Solution.SolutionBuild.StartupProjects = webProject.UniqueName;
                Properties properties = webProject.Properties;
                ProjectItem aspxTestPage = this.GetAspxTestPage(webProject);
                if (aspxTestPage != null)
                {
                    properties.Item("WebApplication.StartPageUrl").Value = aspxTestPage.Name;
                    properties.Item("WebApplication.DebugStartAction").Value = 1;
                }
                if (silverlightProject != null)
                {
                    IVsHierarchy hierarchy;
                    IVsHierarchy hierarchy2;
                    silverlightProject.Properties.Item("SilverlightProject.LinkedServerProject").Value = webProject.FullName;
                    Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = this._dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
                    IVsSolution service = null;
                    using (ServiceProvider provider2 = new ServiceProvider(sp))
                    {
                        service = provider2.GetService(typeof(IVsSolution)) as IVsSolution;
                    }
                    if (((service.GetProjectOfUniqueName(webProject.UniqueName, out hierarchy) == 0) && (hierarchy != null)) && (service.GetProjectOfUniqueName(silverlightProject.UniqueName, out hierarchy2) == 0))
                    {
                        (hierarchy as IVsSilverlightProjectConsumer).LinkToSilverlightProject("ClientBin", true, false, hierarchy2 as IVsSilverlightProject);
                    }
                }
            }
            FileInfo info = new FileInfo(webProject.FullName);
            string directoryName = info.DirectoryName;
            ProjectItem item2 = silverlightProject.ProjectItems.AddFolder("Web", null).ProjectItems.AddFolder("Resources", null);
            foreach (string str6 in Directory.GetFiles(Path.Combine(directoryName, "Resources"), "*.resx"))
            {
                item2.ProjectItems.AddFromFile(str6).Properties.Item("CustomTool").Value = "PublicResXFileCodeGenerator";
            }
            SolutionBuild solutionBuild = this._solution2.SolutionBuild;
            if (silverlightProject != null)
            {
                solutionBuild.BuildProject(solutionBuild.ActiveConfiguration.Name, silverlightProject.UniqueName, true);
            }
            this._solution2.FindProjectItem("MainPage.xaml").Open("{00000000-0000-0000-0000-000000000000}");
        }

        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            this._dte2 = (DTE2) automationObject;
            this._solution2 = (Solution2) this._dte2.Solution;
            this._replacementsDictionary = replacementsDictionary;
            this._replacementsDictionary["$targetsilverlightversion$"] = TemplateUtilities.GetSilverlightToolsVersion();
            this._dte2.Globals["safeclientprojectname"] = replacementsDictionary["$safeprojectname$"];
            this._webProjectName = this._replacementsDictionary["$safeprojectname$"] + ".Web";
            this._customParams = customParams;
            Array source = null;
            try
            {
                source = (Array) this._dte2.ActiveSolutionProjects;
            }
            catch (COMException)
            {
            }
            Project project = (source == null) ? null : source.OfType<Project>().FirstOrDefault<Project>();
            if ((project != null) && (project.Kind == "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}"))
            {
                this._selectedSolutionFolder = project;
            }
        }

        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }
    }
}

